<template>
    <div class="upload-container">
        <el-button icon='upload'  @click=" dialogVisible=true" type="info" v-if="!getOnlyLook">上传图片
        </el-button>
          <el-dialog
            :visible.sync="dialogVisible"
            title="图片上传"
            width="346px"
            >
            <el-upload
                    ref="upload"
                    class="editor-slide-upload"
                    action=""
                    :auto-upload="false"
                    :data="dataObj"
                    :multiple="true"
                    :file-list="fileList"
                    :show-file-list="true"
                    list-type="picture-card"
                    :on-remove="handleRemove"
                    :on-success="handleImageScucess"
                    :on-change="change"
                    accept="image/jpeg,image/gif,image/png,image/bmp"
                    >
                    <!--action="/api/productLine/saveImgInfo.do"-->
                <el-button size="small" type="info">点击上传</el-button>
            </el-upload>
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="info" @click="handleSubmit">确 定</el-button>
          </el-dialog>
    </div>
</template>
<script>
    // import { getToken } from 'api/qiniu';
    import AuthStorage from '@/services/storage.js'
    import { md5 } from '@/utilities/crypto' // 加密
    export default {
      name: 'editorSlideUpload',
      props: {
        color: {
          type: String,
          default: '#20a0ff'
        }
      },
      data() {
        return {
          dialogVisible: false,
          dataObj: { token: AuthStorage.token, key: '' },
          list: [],
          fileList: [],
          arr: [],
          uids: []
        };
      },
      computed: {
        getOnlyLook () {
          return this.$store.state.onlyLook
        }
      },
      methods: {
        change (file, fileList) {
        	if(fileList.length > 1){
	    		this.$message.warning('当前限制选择 1个文件,多张图片覆盖第一张');
	    		var thisNode = document.getElementsByClassName("el-upload-list__item")[0];
	    		thisNode.parentNode.removeChild(thisNode);
	    	}
	    	var isJPG = ""
	    	  if(file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'){
	    		  isJPG = true
	    	  }else{
	    		  isJPG = false
	    	  }
	        const isLt2M = file.size / 1024 / 1024 < 2;
	
	        if (!isJPG) {
	          this.$message.error('上传图片只能是 JPG/png 格式!');
	        }
	        if (!isLt2M) {
	          this.$message.error('上传图片大小不能超过 2MB!');
	        }
	        return isJPG && isLt2M;
          const _self = this
          let readFile = new FileReader()
          readFile.readAsDataURL(file.raw)
          readFile.onload = function () {
            _self.list.push(this.result)
            _self.uids.push(file.uid)
          }
          // console.log(_self.list)
        },
        handleSubmit(file) {
//        const arr = this.list.map(v => v);
//        this.list = [];
//        this.fileList = [];
        this.getFromData()
        this.dialogVisible = false;
//		  this.$emit('successCBK', arr);
        },
        handleRemove(file) {
          const uid = file.uid;
          for (let i = 0, len = this.uids.length; i < len; i++) {
            if (this.uids[i] === uid) {
              this.uids.splice(i, 1);
              this.list.splice(i, 1);
              return
            }
          }
        },
        handleImageScucess(response, file) {
          // this.list.push({ url: file.response.data });
        },
        beforeUpload() {
          const _self = this;
          return new Promise((resolve, reject) => {
            getToken().then(response => {
              const key = response.data.qiniu_key;
              const token = response.data.qiniu_token;
              _self._data.dataObj.token = token;
              _self._data.dataObj.key = key;
              this.list.push({ key, url: response.data.qiniu_url });
              resolve(true);
            }).catch(err => {
              console.log(err);
              reject(false)
            });
          });
        },
        signature(data) {
		  return md5(data)
		},
        getFromData(){
			let formData = new FormData();
	    	let token = sessionStorage.getItem('token');
	    	let data = "{}"
	    	let a = new Date();
		  	let btime= a .getTime();
			  var signs = "data="+data+"&stmb="+btime;
	    	formData.append("uploadImg", document.getElementsByClassName("el-upload__input")[0].files[0]);
	    	formData.append("version", "");
	    	formData.append("data", data);
	    	formData.append("token", token);
	    	formData.append("stmb", btime);
	    	formData.append('sign', this.signature(signs))
		    var oReq = new XMLHttpRequest();
        oReq.open("POST", "/ecshop/console/upload/uploadImg.do", true);
        oReq.send(formData);
        oReq.onreadystatechange = () => {//在这里指定上传成功的回调函数，接受返回值  
                if (oReq.readyState == 4 && oReq.status == 200) {  
                    let res = JSON.parse(oReq.responseText);  
                    if(res.rspCode){
                        if(res.rspCode == "0000"){
                          this.$emit('successCBK', res.data);
                          this.$emit("close", true);
                        }else{
                          this.$message({
                            showClose: true,
                            message: res.rspMsg,
                            type: "error"
                          });
                        } 
                    }
                }
            };
      },
      }
    };
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .dialogImg{
      width: 400px;
    }
    .upload-container {
        .editor-slide-upload {
            margin-bottom: 20px;
        }
    }
</style>

